﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AmiEmuLib.AmigaConfiguration;
using AmiEmuLib.AmigaMachine;
using System.Xml;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Collections;
using TomanuExtensions;

namespace AmiEmuLib.Configuration.AmigaMemoryMap
{
    /// <summary>
    /// Memory map of specified amiga model. Loaded from xml. Can be modified.
    /// </summary>
    [DebuggerDisplay("Model = {Model}, Banks = {Count}")]
    public class MemoryMap
    {
        /// <summary>
        /// Amiga model for which is this memory map.
        /// </summary>
        public AmigaModel AmigaModel;

        /// <summary>
        /// List of memory map chunks.
        /// </summary>
        private List<MemoryMapChunk> m_chunks = new List<MemoryMapChunk>();


        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="a_reader"></param>
        internal MemoryMap(XmlReader a_reader)
        {
            ReadXml(a_reader);
        }

        /// <summary>
        /// Read xml.
        /// </summary>
        /// <param name="a_reader"></param>
        private void ReadXml(XmlReader a_reader)
        {
            AmigaModel = a_reader.GetAttributeEnum<AmigaModel>("AmigaModel");

            a_reader.ReadStartElement(GetType().Name);

            while (a_reader.IsStartElement())
                m_chunks.Add(new MemoryMapChunk(a_reader));

            a_reader.ReadEndElement();
        }

        /// <summary>
        /// Write memory to xml. For development use only.
        /// </summary>
        /// <param name="a_writer"></param>
        internal void WriteXml(XmlWriter a_writer)
        {
            a_writer.WriteStartElement(GetType().Name);

            a_writer.WriteAttribute("AmigaModel", AmigaModel);

            foreach (var def_bank in m_chunks)
            {
                a_writer.WriteStartElement(def_bank.Type.ToString());
                a_writer.WriteHexAttribute("Address", def_bank.Address);
                a_writer.WriteAttribute("Size", def_bank.Size);
                a_writer.WriteEndElement();
            }

            a_writer.WriteEndElement();
        }

        /// <summary>
        /// List of memory map chunks.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<MemoryMapChunk> Chunks
        {
            get
            {
                return m_chunks;
            }
        }

        /// <summary>
        /// Return map chunk from index.
        /// </summary>
        /// <param name="a_index"></param>
        /// <returns></returns>
        public MemoryMapChunk this[int a_index]
        {
            get
            {
                return m_chunks[a_index];
            }
        }
    }
}
